package com.hsyt.pms.controller;


import com.hsyt.pfc.support.util.LoggerUtil;
import com.hsyt.pms.api.entity.common.Result;
import com.hsyt.pms.api.entity.system.PfAdmin;
import com.hsyt.pms.api.enums.ErrorCode;
import com.hsyt.pms.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author maoze@hsyutai.com
 * @Description
 * @Date 19:55 2019/3/31
 * @Param
 * @return
 **/
@Slf4j
@Controller
public class LoginController extends BaseController {


    private final String isPhone = "^((12[0-9])|(13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";

    /*@Resource
    PfUdbAuthService pfUdbAuthService;*/

//    @Resource
//    ImageCodeUtil imageCodeUtil;
//
//    @Resource
//    PfRedisService pfRedisService;
//
//    @Resource
//    PfUserService pfUserService;

//    @Resource
//    PfHosDoctorService pfHosDoctorService;

//    @Resource
//    RestConfig restConfig;

    @RequestMapping("")
    public String projectIndex(ModelMap model, HttpServletRequest request){
        PfAdmin pfAdmin = getSessionUser(request);
        if(pfAdmin != null){
            return "forward:/index";
        }
        return "home";
    }

    @RequestMapping("login")
    public String login(ModelMap model, HttpServletRequest request){
        return "home";
    }

    /**
     * @Description: 生成扫码登录二维码
     * @Return: 
     * @Param: 
     * @Author: caiyl@hsyuntai.com
     * @Date: 2018/1/30 10:09
     */
    @RequestMapping("loginScanCode")
    @ResponseBody
    public Result loginScanCode(HttpServletRequest request){
        Result result = new Result(true, null, null);
        /*try {
            String authKey = UUID.randomUUID().toString().replaceAll("-", "");
            //生产二维码信息至redis
            CfgQr cfgQr = new CfgQr();
            String qrInfo = new StringBuilder(restConfig.getQrCenter()).append(authKey).toString();
            String redisKey = new StringBuilder(PfProdConstant.REDIS_KEY_QR).append(authKey).toString();
            //暂定写死的产品编码
            cfgQr.setPrdCode(PfProdConstant.SESSION_INFO_DCT_PRD_CODE);
            cfgQr.setQrType(QrTypeEnum.PAGE.getCode());
            cfgQr.setPageCode(PageCodeEnum.PLATFORM_LOGIN.getCode());
            //传参的业务数据-此处为authKey（uuid）
            cfgQr.setResId(authKey);
            //二维码数据写至redis
            this.pfRedisService.set(redisKey, JSON.toJSONString(cfgQr), PfProdConstant.REDIS_KEY_QR_SPIRETIME);
            //二维码信息(qr地址+uuid)
            result.setDisplayMsg(qrInfo);
            request.getSession().setAttribute(PfProdConstant.SESSION_SCAN_AUTH_KEY, authKey);
        }  catch(Exception e) {
            String errMsg = StringUtils.isBlank(e.getMessage()) ? e.getMessage() : PfProdConstant.COMMON_LOGIN_FAIL_MSG;
            LoggerUtil.error(LOGGER, "LoginController-loginScanCode error: {0},e: {1}", errMsg, e);
            result.change(false, errMsg, errMsg);
        }*/
        return result;
    }

    /**
     * @Description: 验证扫码登录
     * @Return: 
     * @Param: 
     * @Author: caiyl@hsyuntai.com
     * @Date: 2018/1/30 10:09
     */
    /*@RequestMapping("loginCheckScanCode")
    @ResponseBody
    public Result loginCheckScanCode(HttpServletRequest request){
        Result result = new Result(true, null, null);
        try {
            String authKey = (String) request.getSession().getAttribute(PfProdConstant.SESSION_SCAN_AUTH_KEY);
            LoggerUtil.info(LOGGER, "LoginController-loginCheckScanCode authKey: {0}", authKey);
            if(StringUtils.isBlank(authKey)){
                return result.change(false, null, PfProdConstant.COMMON_LOGIN_FAIL_MSG);
            }
            //获取udb扫码登录结果
            ResultModel<CurrentUser> resultModel = this.pfUdbAuthService.tryScanCodeAuth(authKey);
            LoggerUtil.info(LOGGER, "LoginController-loginCheckScanCode resultModel: {0}", JSON.toJSONString(resultModel));
            if(!resultModel.isResult() || resultModel.getData() == null || resultModel.getData().getUsId() == null){
                return result.change(false, resultModel.getKind(), resultModel.getMsg());
            }
            PfAdmin pfAdmin = new PfAdmin();
            pfAdmin.setUdbUsId(resultModel.getData().getUsId());
            pfAdmin.setUdbPhoneNo(String.valueOf(resultModel.getData().getPhoneNo()));
            pfAdmin.setUdbHeadPhoto(resultModel.getData().getHeadPhotoUrl());
//                pfAdmin.setUdbRealName(resultModel.getData().getNickName());
            //关联查询平台用户
            getPfUser(pfAdmin);
            if(pfAdmin.getId() == null && pfAdmin.getDocId() == null){
                return result.change(false, ErrorCode.LOGIN_PLATFORM_USER_NULL.getCode(), ErrorCode.LOGIN_PLATFORM_USER_NULL.getName());
            }
            setSessionUser(request, pfAdmin);
            //清除redis错误记录
            this.pfRedisService.kDel(PfProdConstant.PLATFORM_LOGIN_ERROR_TIMES + pfAdmin.getUdbPhoneNo());
        }  catch(Exception e) {
            String errMsg = StringUtils.isBlank(e.getMessage()) ? e.getMessage() : PfProdConstant.COMMON_LOGIN_FAIL_MSG;
            LoggerUtil.error(LOGGER, "LoginController-loginCheckScanCode error: {0},e: {1}", errMsg, e);
            result.change(false, errMsg, errMsg);
        }
        return result;
    }*/

    private void getPfUser(PfAdmin pfAdmin){
        /*//查询是否为医生
        PfHosDoctorDto pfHosDoctorParam = new PfHosDoctorDto();
        pfHosDoctorParam.setAuthId(pfAdmin.getUdbUsId());
        PfHosDoctorDto pfHosDoctorDto = this.pfHosDoctorService.getOneHosDoctor(pfHosDoctorParam);
        if(pfHosDoctorDto != null  && pfHosDoctorDto.getState() == 1){
            //医生用户信息
            if(DoctorStatusEnum.ENABLED.getCode().equals(pfHosDoctorDto.getState())){
                //医生可用
                pfAdmin.setDocId(pfHosDoctorDto.getDocId());
                pfAdmin.setDocName(pfHosDoctorDto.getName());
                pfAdmin.setPrdCode(PfProdConstant.SESSION_INFO_YUN_PRD_CODE);
                pfAdmin.setTelephone(pfHosDoctorDto.getPhoneNo());
                pfAdmin.setUserName(pfHosDoctorDto.getName());
                pfAdmin.setUserType(UserTypeEnum.ADMIN.getCode());
                pfAdmin.setRoleId(PfProdConstant.DEFAULT_DOC_ROLE_ID);
                pfAdmin.setHosId(pfHosDoctorDto.getHosId());
            }
        }*/
        //查询权限
//        PfUserDto pfUserParam = new PfUserDto();
//        pfUserParam.setTelephone(pfAdmin.getUdbPhoneNo());
//        List<PfUserDto> pfUserList = this.pfUserService.selectByDto(pfUserParam);
//        if(CollectionUtils.isNotEmpty(pfUserList) && pfUserList.size() == 1){
//            //获取平台用户信息至pfAdmin
//            PfUserDto pfUserDto = pfUserList.get(0);
//            if(FreezeStatusEnum.ENABLED.getCode().equals(pfUserDto.getStatus())){
//                //管理员状态正常
//                pfAdmin.setId(pfUserDto.getId());
//                pfAdmin.setPrdCode(PfProdConstant.SESSION_INFO_YUN_PRD_CODE);
//                pfAdmin.setTelephone(pfUserDto.getTelephone());
//                pfAdmin.setEmail(pfUserDto.getEmail());
//                pfAdmin.setUserName(pfUserDto.getUserName());
//                pfAdmin.setStatus(pfUserDto.getStatus());
//                pfAdmin.setUserType(pfUserDto.getUserType());
//                pfAdmin.setRoleId(pfUserDto.getRoleId());
//            }
//        }
    }

    /**
     * @Description: 登录操作
     * @Return: 
     * @Param: 
     * @Author: caiyl@hsyuntai.com
     * @Date: 2018/1/2 9:34
     */
    @RequestMapping("loginIn")
    @ResponseBody
    public Result loginIn(HttpServletRequest request, String userName, String password, String vcode){
        Result result = new Result(true, null, null);
        PfAdmin pfAdmin = new PfAdmin();
        try {
//            if(StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(vcode)){
//                return result.change(false, ErrorCode.LOGIN_INFO_NULL.getCode(), ErrorCode.LOGIN_INFO_NULL.getName());
//            }
//            if(!vcode.equalsIgnoreCase((String) request.getSession().getAttribute(imageCodeUtil.getSessionKey())) ){
//                return result.change(false, ErrorCode.LOGIN_VCODE_ERROR.getCode(), ErrorCode.LOGIN_VCODE_ERROR.getName());
//            }
            //检查当前用户是否
//            String times = this.pfRedisService.get(PfProdConstant.PLATFORM_LOGIN_ERROR_TIMES + userName);
//            Integer errorTimes = StringUtils.isNotBlank(times) ? Integer.valueOf(times) : 0;
//            if(StringUtils.isNotBlank(times) && errorTimes >= 5){
//                return result.change(false, ErrorCode.ERROR_TIMES_MAX.getCode(), ErrorCode.ERROR_TIMES_MAX.getName());
//            }
//            // 手机的登录
//            PfUserDto pfUserParam = new PfUserDto();
//            PfUserDto dbUserInfo = new PfUserDto();
//            List<PfUserDto> pfUserList = new ArrayList<PfUserDto>();
//             if(userNameRegex(userName)){
//                pfUserParam.setTelephone(userName);
//                pfUserList = this.pfUserService.selectByDto(pfUserParam);
//            }else{
//                //使用平台用户体系登录
//                pfUserParam.setUserName(userName);
//                pfUserList = this.pfUserService.selectByDto(pfUserParam);
//            }
//            if(CollectionUtils.isEmpty(pfUserList) || !(dbUserInfo = pfUserList.get(0)).getPassword().equals(password)){
//                //用户名或密码错误，记录至redis
//                this.pfRedisService.set(PfProdConstant.PLATFORM_LOGIN_ERROR_TIMES + userName, String.valueOf(++errorTimes), PfProdConstant.REDIS_KEY_LOGIN_ERROR_TIMES_SPIRETIME);
//                String userNameOrPasswordErrorMsg = MessageFormat.format(ErrorCode.ERROR_SURPLUS_TIMES.getName(), 5-errorTimes);
//                return result.change(false, ErrorCode.ERROR_SURPLUS_TIMES.getCode(), errorTimes == 5 ? ErrorCode.ERROR_TIMES_MAX.getName() : userNameOrPasswordErrorMsg);
//            }
//            if(!FreezeStatusEnum.ENABLED.getCode().equals(dbUserInfo.getStatus())){
//                //管理员状态异常
//                return result.change(false, ErrorCode.LOGIN_USERNAME_STATE_EXCEPTION.getCode(), ErrorCode.LOGIN_USERNAME_STATE_EXCEPTION.getName());
//            }
//            // 正常
//            pfAdmin.setId(dbUserInfo.getId());
////            pfAdmin.setPrdCode(PfProdConstant.SESSION_INFO_YUN_PRD_CODE);
//            pfAdmin.setTelephone(dbUserInfo.getTelephone());
//            pfAdmin.setEmail(dbUserInfo.getEmail());
//            pfAdmin.setUserName(dbUserInfo.getUserName());
//            pfAdmin.setStatus(dbUserInfo.getStatus());
//            pfAdmin.setUserType(dbUserInfo.getUserType());
////            pfAdmin.setIdList(dbUserInfo.getIdList());
//            pfAdmin.setIsvPid(dbUserInfo.getIsvPid());
//            // TODO: 2018/5/16   权限问题
//            if (UserTypeEnum.SUPER.getCode().equals(dbUserInfo.getUserType())) {//仅super类型用户无需控制
//            } else {
//                pfAdmin.setTabList(pfUserService.getRefTabByUserId(dbUserInfo.getId()));
//                pfAdmin.setBtnList(pfUserService.getRefBtnByUserId(dbUserInfo.getId()));
//                pfAdmin.setBtnMap(pfUserService.getRefBtnMapByUserId(dbUserInfo.getId()));
//            }

            /*
            集成Udb登录逻辑
            YuntaiLoginResponse yuntaiLoginResponse = this.pfUdbAuthService.login(userName, password, pfAdmin);
            if(yuntaiLoginResponse == null || !yuntaiLoginResponse.isResult()){
                if(ErrorCode.UDB_LOGIN_USERNAME_ERROR_CODE.getCode().equals(yuntaiLoginResponse.getCode()) || ErrorCode.UDB_LOGIN_PASSWORD_ERROR_CODE.getCode().equals(yuntaiLoginResponse.getCode())){
                    //用户名或密码错误，记录至redis
                    this.pfRedisService.set(PfProdConstant.PLATFORM_LOGIN_ERROR_TIMES + userName, String.valueOf(++errorTimes), PfProdConstant.REDIS_KEY_LOGIN_ERROR_TIMES_SPIRETIME);
                    String userNameOrPasswordErrorMsg = MessageFormat.format(ErrorCode.ERROR_SURPLUS_TIMES.getName(), 5-errorTimes);
                    return result.change(false, ErrorCode.ERROR_SURPLUS_TIMES.getCode(), errorTimes == 5 ? ErrorCode.ERROR_TIMES_MAX.getName() : userNameOrPasswordErrorMsg);
                }
                return result.change(false, yuntaiLoginResponse == null?ErrorCode.LOGIN_ERROR.getCode():yuntaiLoginResponse.getCode(),
                        yuntaiLoginResponse == null?ErrorCode.LOGIN_ERROR.getName():yuntaiLoginResponse.getMsg());
            }
            pfAdmin.setUdbAccessToken(yuntaiLoginResponse.getAccessToken());
            YuntaiUserInfoResponse yuntaiUserInfoResponse = this.pfUdbAuthService.getUserInfo(pfAdmin);
            if(yuntaiUserInfoResponse == null || !yuntaiUserInfoResponse.isResult()){
                return result.change(false, yuntaiUserInfoResponse == null?ErrorCode.LOGIN_ERROR.getCode():yuntaiUserInfoResponse.getCode(),
                        yuntaiUserInfoResponse == null?ErrorCode.LOGIN_ERROR.getName():yuntaiUserInfoResponse.getMsg());
            }
            pfAdmin.setUdbAddress(yuntaiUserInfoResponse.getAddress());
            pfAdmin.setUdbEmail(yuntaiUserInfoResponse.getEmail());
            pfAdmin.setUdbHeadPhoto(yuntaiUserInfoResponse.getHeadPhoto());
            pfAdmin.setUdbPhoneNo(yuntaiUserInfoResponse.getPhoneNo());
            pfAdmin.setUdbRealName(yuntaiUserInfoResponse.getRealName());
            pfAdmin.setUdbSex(yuntaiUserInfoResponse.getSex());
            pfAdmin.setUdbWorkUnit(yuntaiUserInfoResponse.getWorkUnit());
            pfAdmin.setUdbUsId(Long.valueOf(yuntaiUserInfoResponse.getUsId()));
            //关联查询平台用户
            getPfUser(pfAdmin);
            if(pfAdmin.getId() == null && pfAdmin.getDocId() == null){
                return result.change(false, ErrorCode.LOGIN_PLATFORM_USER_NULL.getCode(), ErrorCode.LOGIN_PLATFORM_USER_NULL.getName());
            }*/

//            setSessionUser(request, pfAdmin);
//            //清除redis错误记录
//            this.pfRedisService.kDel(PfProdConstant.PLATFORM_LOGIN_ERROR_TIMES + userName);
        }  catch(Exception e) {
//            String errMsg = StringUtils.isBlank(e.getMessage()) ? e.getMessage() : PfProdConstant.COMMON_LOGIN_FAIL_MSG;
//                LoggerUtil.error(log, "LoginController-loginIn error: {0},e: {1}", errMsg, e);
//            result.change(false, errMsg, errMsg);
        }
            return result;
    }

    @RequestMapping(value = "/loginVcode", method = RequestMethod.GET)
    @ResponseBody
    public String loginVcode(HttpServletRequest request, HttpServletResponse response) {
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        try {
            ServletOutputStream sos = response.getOutputStream();
//            ImageIO.write(imageCodeUtil.getImage(request), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            LoggerUtil.error(log, "LoginController-loginVcode error: {0}", e);
        }
        return null;
    }

    @RequestMapping("loginTimeout")
    public String loginTimeout(ModelMap model, HttpServletRequest request){
        return "common/loginTimeout";
    }

    @RequestMapping(value = "/loginOut")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("sessionUser");
        return "redirect:/login";
    }

    @RequestMapping(value = "/loginPermission")
    public String loginPermission(){
        return "common/loginPermission";
    }


//    private Boolean userNameRegex(String userName){
//        Pattern p = Pattern.compile(isPhone);
//        Matcher m = p.matcher(userName);
//        return m.matches();
//    }

}
